package view.drawing;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;

import model.ModelObject;

public abstract class DrawState<T extends ModelObject> {
	
	private T mModel;
	private State<T> mState;
	
	private int mIndex;
	

	public DrawState(T model) {
		this.mModel = model;

	}
	
	public void update(long elapsedTime) {
		State<T> state = getState();
		
		if (state != null) {
			state.update(elapsedTime, mModel, this);
		}
	}
	
	public State<T> getState() {
		if (this.mState == null) {
			this.mState = this.getDefaultState();
		}
		return (mState);
	}
	
	public void setState(State<T> state) {
		mState = state;
	}
	
	public String getStateString() {
		State<T> state = getState();
		if (state == null) return "";
		return (state.getStateString());
	}
	
	public void setIndex(int index) {
		mIndex = index;
	}
	
	public void resetIndex() {
		mIndex = 0;
	}
	
	public int getIndex() {
		return (mIndex);
	}
	
	public void resetState() {
		setState(getDefaultState());
		resetIndex();
	}
	
	public void draw(Graphics g, Rectangle destRect) {
		DrawManager dm = DrawManager.getInstance();
		
		SpriteSheetSet modelSet = dm.getSpriteSheetSet(mModel.getName());
		
		if (modelSet == null) {
			System.err.format("Unable to get the SpriteSheetSet for Model '%s'!\n", mModel.getName());
			return;
		}
		SpriteSheet sheet = modelSet.getSpriteSheet(this.getStateString());
		
		if (sheet == null) {
			System.err.format("Unable to get the SpriteSheet for Model '%s' and state '%s'!\n", mModel.getName(), this.getStateString());
			return;
		}
		
		Rectangle bounds = sheet.getFrameBounds(this.getIndex());
		Image img = sheet.getImage();
		g.drawImage(img, destRect.x, destRect.y, destRect.x + destRect.width, destRect.y + destRect.height,
					bounds.x, bounds.y, bounds.width, bounds.height, null);
	}
	
	public void draw(Graphics g, Point upperLeft) {
DrawManager dm = DrawManager.getInstance();
		
		SpriteSheetSet modelSet = dm.getSpriteSheetSet(mModel.getName());
		
		if (modelSet == null) {
			System.err.format("Unable to get the SpriteSheetSet for Model '%s'!\n", mModel.getName());
			return;
		}
		SpriteSheet sheet = modelSet.getSpriteSheet(this.getStateString());
		
		if (sheet == null) {
			System.err.format("Unable to get the SpriteSheet for Model '%s' and state '%s'!\n", mModel.getName(), this.getStateString());
			return;
		}
		
		Rectangle bounds = sheet.getFrameBounds(this.getIndex());
		Image img = sheet.getImage();
		
//		g.drawImage(img, upperLeft.x, upperLeft.y, null);
		g.drawImage(img, upperLeft.x, upperLeft.y, upperLeft.x + bounds.width, upperLeft.y + bounds.height,
					bounds.x, bounds.y, bounds.width, bounds.height, null);
	}
	
	public abstract State<T> getDefaultState();
	
	
}
